//
//  OtherPublishViewController.m
//  cityStar
//
//  Created by Hancong on 15/2/11.
//  Copyright (c) 2015年 tiny. All rights reserved.
//

#import "VideoPublishViewController.h"
#import "selectDistrict.h"
#import "RIButtonItem.h"
#import "UIAlertView+Blocks.h"
#import "UIActionSheet+Blocks.h"
#import "UpLoadImageManager.h"
#import "UIColor+HexColors.h"
#import "VideoViewController.h"

@interface VideoPublishViewController ()<UIPickerViewDelegate,UITextViewDelegate,UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>

@property (nonatomic,strong) NSArray *arrayName;
@property (nonatomic,strong) NSArray *arrayid;
@property (nonatomic,strong) NSString *videoType;
@property (nonatomic,strong) NSString *strAddressID;
@property (nonatomic,assign) int segmentIndex;
@property (nonatomic,strong) NSString *payType;
@property (nonatomic,assign) int buttonTag;
@property (nonatomic,strong) NSMutableDictionary *dictPhotoIDs;

@end

@implementation VideoPublishViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setUpViews];
    [self addBackButton];
    [self addRightButtonWithTitle:@"发布须知" actionBlock:^{
        
    }];

}
- (IBAction)seleSegment:(UISegmentedControl *)sender {
    self.segmentIndex = sender.selectedSegmentIndex+1;
}

#pragma mark - setUp
-(void)setUpViews
{
    self.title = @"租售";
    self.payType = @"12";
    self.videoType = @"1";
    self.strAddressID = [NSString stringWithFormat:@"%@",self.arrayid[0]];

    self.dictPhotoIDs = [[NSMutableDictionary alloc]init];
    self.scrollerView.contentSize = CGSizeMake(320, 880);
    self.segFrom.height = 18;
    self.fieldHouse01.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.fieldHouse02.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.fieldHouse03.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.fieldHouse01.layer.borderWidth = 0.5f;
    self.fieldHouse02.layer.borderWidth = 0.5f;
    self.fieldHouse03.layer.borderWidth = 0.5f;
    
    self.arrayName = [[NSArray alloc]init];
    self.arrayid = [[NSArray alloc]init];
    self.textDetail.placeholder = @"请输入房源详细情况，如楼层，朝向等等";
    self.textDetail.placeholderColor = [UIColor colorWithWhite:0.797 alpha:1.000];
    self.textDetail.delegate = self;
    self.arrayName  = [selectDistrict shardDistrictInfo].DistrictNameArray;
    self.arrayid =[selectDistrict shardDistrictInfo].DistrictIdArray;
    UIPickerView *typePickerView = [[UIPickerView alloc]init];
    typePickerView.delegate = self;
    typePickerView.tag = 0;
    self.fieldType.inputView = typePickerView;

    UIPickerView *addressPickerView = [[UIPickerView alloc]init];
    addressPickerView.delegate = self;
    addressPickerView.tag = 1;
    self.fieldAddress.inputView = addressPickerView;
    
    UIPickerView *payPickerView = [[UIPickerView alloc]init];
    payPickerView.delegate = self;
    payPickerView.tag = 2;
    self.fieldPayType.inputView = payPickerView;
    
    UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
    [topView setBarStyle:UIBarStyleDefault];
    
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];
    
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace,doneButton,nil];
    
    [topView setItems:buttonsArray];
    [self.fieldType setInputAccessoryView:topView];
    [self.fieldAddress setInputAccessoryView:topView];
    [self.fieldPayType setInputAccessoryView:topView];
    
}

-(void)dismissKeyBoard
{
    [self.fieldType resignFirstResponder];
    [self.fieldAddress resignFirstResponder];
    [self.fieldPayType resignFirstResponder];
}

#pragma mark - pickerViewDelegate
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
        return 1;
}

-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (pickerView.tag == 0) {
        return 3;
    }else if(pickerView.tag == 1){
        return self.arrayName.count;
    }else{
        return 4;
    }
}

-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (pickerView.tag == 0) {
        if (row == 0) {
            return @"整租";
        }else if (row == 1){
            return @"合租";
        }else
        {
            return @"出售";
        }
    }else if(pickerView.tag == 1){
        return self.arrayName[row];
    }else{
        if (row == 0) {
            return @"付一押二";
        }else if (row == 1){
            return @"付三押一";
        }else if (row == 2){
            return @"半年付不押";
        }else{
            return @"年付不压";
        }
    }
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (pickerView.tag == 0) {
        if (row == 0) {
            self.fieldType.text = @"整租";
            self.videoType = @"1";
        }else if (row == 1){
            self.fieldType.text = @"合租";
            self.videoType = @"2";
        }else{
            self.fieldType.text = @"出售";
            self.videoType = @"3";
        }
    }else if(pickerView.tag == 1){
        NSString *strname = [NSString stringWithFormat:@"%@",self.arrayName[row]];
        self.strAddressID = [NSString stringWithFormat:@"%@",self.arrayid[row]];
        self.fieldAddress.text = strname;
    }else{
        if (row == 0) {
            self.fieldPayType.text = @"付一押二";
            self.payType = @"12";
        }else if (row == 1){
            self.fieldPayType.text = @"付三押一";
            self.payType = @"31";

        }else if (row == 2){
            self.fieldPayType.text = @"半年付不押";
            self.payType = @"60";

        }else{
            self.fieldPayType.text = @"年付不压";
            self.payType = @"00";

        }
    }
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    switch (textField.tag) {
        case 3:
        {
            self.fieldAddress.text = self.arrayName[0];
        }
            break;
        case 4:
        {
            self.fieldType.text = @"整租";
        }
            break;
        case 6:
        {
            [UIView animateWithDuration:0.3f animations:^{
                self.scrollerView.contentOffset = CGPointMake(0, 100);
            }];
        }
            break;
        case 7:
        {
            [UIView animateWithDuration:0.3f animations:^{
                self.scrollerView.contentOffset = CGPointMake(0, 150);
            }];
//            textField.text = self.arrayName[0];
        }
            break;
        case 8:
        {
            [UIView animateWithDuration:0.3f animations:^{
                self.scrollerView.contentOffset = CGPointMake(0, 200);
                self.fieldPayType.text = @"押一付二";
            }];

        }
            break;
        case 9:
        {
            [UIView animateWithDuration:0.3f animations:^{
                self.scrollerView.contentOffset = CGPointMake(0, 250);
            }];
        }
            break;
        case 10:
        {
            [UIView animateWithDuration:0.3f animations:^{
                self.scrollerView.contentOffset = CGPointMake(0, 300);
            }];
        }
            break;
            
        default:
            break;
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

-(IBAction)btnPublish_Touch:(id)sender
{
    NSString *errMsg;
    if (self.fieldTitle.text.length == 0) {
        errMsg = @"请输入标题";
    }else if (self.fieldType.text.length == 0){
        errMsg = @"请选择类型";
    }else if (self.fieldHouse01.text.length == 0){
        errMsg = @"请输入户型（室）";
    }else if (self.fieldHouse02.text.length == 0){
        errMsg = @"请输入户型（卫）";
    }else if (self.fieldHouse03.text.length == 0){
        errMsg =@"请输入户型（厅）";
    }else if (self.fieldArea.text.length == 0){
        errMsg = @"请输入面积";
    }else if (self.fieldPayType.text.length == 0){
        errMsg = @"请选择付款方式";
    }else if (self.fieldName.text.length == 0){
        errMsg = @"请输入联系人";
    }else if (self.fieldPhone.text.length == 0){
        errMsg = @"请输入联系方式";
    }else if (self.textDetail.text.length == 0){
        errMsg = @"请输入详情描述";
    }
    if (errMsg) {
        BossSystemShowAlertViewWithTitle(errMsg)
        return;
    }

    NSString *cityID = [[NSUserDefaults standardUserDefaults]objectForKey:@"city_code"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    NSDictionary *parameters = @{@"title":self.fieldTitle.text,
                                 @"source":[NSString stringWithFormat:@"%i",self.segmentIndex],
                                 @"category":self.videoType,
                                 @"room":self.fieldHouse01.text,
                                 @"hall":self.fieldHouse02.text,
                                 @"bathroom":self.fieldHouse03.text,
                                 @"area":self.fieldArea.text,
                                 @"money":self.fieldMoney.text,
                                 @"pay_type":self.payType,
                                 @"district":self.strAddressID,
                                 @"district_name":self.fieldAddress.text,
                                 @"contact":self.fieldName.text,
                                 @"phone":self.fieldPhone.text,
                                 @"description":self.textDetail.text,
                                 @"city":cityID?cityID:@"122"
                                 };
    [self.dictPhotoIDs addEntriesFromDictionary:parameters];
    [HttpRequestManager postMethod:KInterface_PublishRental parameters:self.dictPhotoIDs completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        DLog(@"%@",response);
        if (success) {
            [SVProgressHUD showSuccessWithStatus:@"发布成功"];
            VideoViewController *videoViewVC = [[VideoViewController alloc]init];
            [self.navigationController pushViewController:videoViewVC animated:YES];
        }else{
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];
}

-(IBAction)getPhoto_Touch:(UIButton *)sender
{
    [self.view endEditing:YES];
    self.buttonTag = (int)sender.tag;
    __block UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    
    RIButtonItem *takePhotoButton = [RIButtonItem itemWithLabel:@"拍照" action:^{
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }];
    RIButtonItem *choosePhotoButton = [RIButtonItem itemWithLabel:@"从相册选取" action:^{
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }];
    
    UIActionSheet *imageSourcePickActionSheet;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        imageSourcePickActionSheet = [[UIActionSheet alloc] initWithTitle:@"添加照片" cancelButtonItem:nil destructiveButtonItem:[RIButtonItem itemWithLabel:@"取消"] otherButtonItems:takePhotoButton,choosePhotoButton,nil];
    }else{
        imageSourcePickActionSheet = [[UIActionSheet alloc] initWithTitle:@"添加照片" cancelButtonItem:nil destructiveButtonItem:[RIButtonItem itemWithLabel:@"取消"] otherButtonItems:choosePhotoButton,nil];
    }
    [imageSourcePickActionSheet showInView:self.view];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
        [picker dismissViewControllerAnimated:YES completion:^{
            switch (self.buttonTag) {
                case 1:
                {
                    [self.btnAddImage01 setImage:editingInfo[UIImagePickerControllerOriginalImage] forState:UIControlStateNormal];
                    [self.btnAddImage01 setTitle:@"" forState:UIControlStateNormal];
                    [self.btnAddImage01 setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
                    [UpLoadImageManager uploadImage:editingInfo[UIImagePickerControllerOriginalImage] withCompltedBlock:^(BOOL success, NSString *urlString) {
                        if (success) {
                            [self.dictPhotoIDs setObject:urlString forKey:@"image[0]"];
                            DLog(@"%@",urlString);
                        }
                    }];
                }
                    
                    break;
                case 2:
                {
                    [self.btnAddImage02 setImage:editingInfo[UIImagePickerControllerOriginalImage] forState:UIControlStateNormal];
                    [self.btnAddImage02 setTitle:@"" forState:UIControlStateNormal];
                    [self.btnAddImage02 setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

                    [UpLoadImageManager uploadImage:editingInfo[UIImagePickerControllerOriginalImage] withCompltedBlock:^(BOOL success, NSString *urlString) {
                        if (success) {
                            [self.dictPhotoIDs setObject:urlString forKey:@"image[1]"];
                            DLog(@"%@",urlString);
                        }
                    }];
                }
                    break;
                case 3:
                {
                    [self.btnAddImage03 setImage:editingInfo[UIImagePickerControllerOriginalImage] forState:UIControlStateNormal];
                    [self.btnAddImage03 setTitle:@"" forState:UIControlStateNormal];
                    [self.btnAddImage03 setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

                    [UpLoadImageManager uploadImage:editingInfo[UIImagePickerControllerOriginalImage] withCompltedBlock:^(BOOL success, NSString *urlString) {
                        if (success) {
                            [self.dictPhotoIDs setObject:urlString forKey:@"image[2]"];
                            DLog(@"%@",urlString);
                        }
                    }];
                }
                    break;
                case 4:
                {
                    [self.btnAddImage04 setImage:editingInfo[UIImagePickerControllerOriginalImage] forState:UIControlStateNormal];
                    [self.btnAddImage04 setTitle:@"" forState:UIControlStateNormal];
                    [self.btnAddImage04 setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

                    [UpLoadImageManager uploadImage:editingInfo[UIImagePickerControllerOriginalImage] withCompltedBlock:^(BOOL success, NSString *urlString) {
                        if (success) {
                            [self.dictPhotoIDs setObject:urlString forKey:@"image[3]"];
                            DLog(@"%@",urlString);
                        }
                    }];
                }
                    break;
                case 5:
                {
                    [self.btnAddImage05 setImage:editingInfo[UIImagePickerControllerOriginalImage] forState:UIControlStateNormal];
                    [self.btnAddImage05 setTitle:@"" forState:UIControlStateNormal];
                    [self.btnAddImage05 setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

                    [UpLoadImageManager uploadImage:editingInfo[UIImagePickerControllerOriginalImage] withCompltedBlock:^(BOOL success, NSString *urlString) {
                        if (success) {
                            [self.dictPhotoIDs setObject:urlString forKey:@"image[4]"];
                            DLog(@"%@",urlString);
                        }
                    }];
                }
                    break;
                    
                default:
                    break;
            }
        }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
